package www.way2inbox.data;

import java.nio.channels.WritableByteChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;

import www.way2inbox.common.PrintMsg;
public class Native_DatabaseHelper extends SQLiteOpenHelper {
	// database name
Context context;
	private static final String DATABASE_NAME = "native_sms";

	// database version
	private static final int DATABASE_VERSION = 1;
	private static SQLiteDatabase myWritableDb;
	// message table

	private static final String MESSAGE_Table = "MESSAGES";
	private static final String ID = "id", SMS_ID = "sms_id",
			M_ADDRESS = "mobileno", MSG = "msg", SEEN = "seen", READ = "read",
			MDate_Time = "Mdatetime", MTYPE = "mtype",M_DELIVERY="mdelivery",MCARRIER="mcarrier";



	private static final String PRIVATE_TABLE = "PRIVATE_SPAM";
	private static final String P_ID = "p_id", P_ADDRESS = "p_mobileno",P_TYPE="P_Type";


    //PUSH NOTIFICATION DATABASE..
    private static final String Push_table="PushDB";
    private static final String Push_ID="_id",
                                Push_name="name",
                                Push_aaddress="Address",
                                Push_message="Message",
                                Push_date="date";

	public Native_DatabaseHelper(Context context) {

		super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_SMS_TABLE = "CREATE TABLE " + MESSAGE_Table + "(" + ID
				+ " INTEGER PRIMARY KEY autoincrement," + SMS_ID + " TEXT,"
				+ M_ADDRESS + " TEXT," + MSG + " TEXT ," + SEEN + " TEXT,"
				+ READ + " TEXT," + MTYPE + " TEXT," + M_DELIVERY + " TEXT,"+ MCARRIER + " TEXT," + MDate_Time + " DATETIME"
				+ ")";
		db.execSQL(CREATE_SMS_TABLE);


		String CREATE_PRIVATE_TABLE = "CREATE TABLE " + PRIVATE_TABLE + "("
				+ P_ID + " INTEGER PRIMARY KEY autoincrement,"
                + P_ADDRESS+ " TEXT,"
                + P_TYPE +" INTEGER "+ ")";
		db.execSQL(CREATE_PRIVATE_TABLE);


        String CREATE_Push_TABLE = "CREATE TABLE " + Push_table + "("
                + Push_ID + " INTEGER PRIMARY KEY autoincrement,"
                + Push_name+ " TEXT,"
                + Push_aaddress+ " TEXT,"
                + Push_message+ " TEXT,"
                + Push_date+ " TEXT"+ ")";
        db.execSQL(CREATE_Push_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

//	public void insertMessage(String smsid,String maddress,String msg,String seen,String read,String mtype,String date,String mCarier) {
//		myWritableDb=getWritableDatabase();
//		ContentValues cv=new ContentValues();
//		cv.put(SMS_ID, smsid);
//		cv.put(M_ADDRESS, maddress);
//		cv.put(MSG, msg);
//		cv.put(SEEN, seen);
//		cv.put(READ, read);
//        cv.put(MTYPE, mtype);
//        cv.put(MCARRIER, mCarier);
//		cv.put(MDate_Time, date);
//		long i=myWritableDb.insert(MESSAGE_Table, null, cv);
//		System.out.println("this is insertion suucess report "+i+"  "+msg);
//	}

    public void insertPush(String name,String maddress,String msg,String date) {
        myWritableDb=getWritableDatabase();
        ContentValues cv=new ContentValues();

        cv.put(Push_aaddress, maddress);
        cv.put(Push_name, name);
        cv.put(Push_message, msg);
        cv.put(Push_date, date);
        long i=myWritableDb.insert(Push_table, null, cv);
        System.out.println("this is insertion suucess report "+i+"  "+msg);
    }

    int count;
    Cursor pushCur;
	public int getPush_uni_count(){
        myWritableDb=this.getWritableDatabase();
        String query="SELECT DISTINCT "+Push_aaddress+" FROM "+Push_table;
        pushCur= myWritableDb.rawQuery(query,null);

        return count=pushCur.getCount();
    }

    public ArrayList<smsfetch>  getPushSMS(){
        ArrayList<smsfetch> result=new ArrayList<smsfetch>();
                myWritableDb=this.getWritableDatabase();
        String query="SELECT * FROM "+Push_table;
        pushCur= myWritableDb.rawQuery(query,null);

        while(pushCur.moveToNext()){
            Log.e("Push Message :",""+pushCur.getString(pushCur.getColumnIndex(Push_name))+"--"+pushCur.getString(pushCur.getColumnIndex(Push_aaddress))+"---"+pushCur.getString(pushCur.getColumnIndex(Push_message)));
            smsfetch obj=new smsfetch();
            obj.set_person(pushCur.getString(pushCur.getColumnIndex(Push_name)));
            obj.setAddress(pushCur.getString(pushCur.getColumnIndex(Push_aaddress)));
            obj.setMsg(pushCur.getString(pushCur.getColumnIndex(Push_message)));
            obj.setTime(pushCur.getString(pushCur.getColumnIndex(Push_date)));
            result.add(obj);
        }

        return result;
    }

    public void delete(String address) {
myWritableDb=this.getWritableDatabase();
myWritableDb.delete(MESSAGE_Table, M_ADDRESS+" =?",new String[]{address});
	}

    public void RemovePush(String address) {
        myWritableDb=this.getWritableDatabase();
        myWritableDb.delete(Push_table, Push_aaddress+" = '"+address+"' or "+Push_aaddress+" = '+91"+address+"'",null);
    }



    public void updatePrivate_Spam(String Address,int type){
        myWritableDb=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(P_TYPE, type);
        myWritableDb.update(PRIVATE_TABLE, values,P_ADDRESS+" =?",new String[]{Address});
    }

/*
* HERE REQUESTFOR IS FOR THE QUERY OF SMS..
* 1- FOR ALL SMS EXCEPT SPAM,PRIVATE SMS GROUP LISTS.
* 2- FOR ONLY PRIVATE SMS GROUP LISTS.
* 3- FOR ONLY SPAM SMS GROUP LISTS
* 4- FOR PERSONAL SMS CHAT ROOM LISTS (PERSONSMS SENT HERE)
*
*the _id a increment the field, starting from 1
the thread_id No. same sender id
address the sender's phone number
the serial number of the person contacts list, strangers to null
date Sent Date
protocol agreement is divided into: 0 SMS_RPOTO, 1 MMS_PROTO
read read 0 Unread, Read
status status -1 received, 0 complete, 64 pending, 128 failed
type
ALL = 0;
INBOX = 1;
SENT = 2;
DRAFT = 3;
Outbox = 4;
FAILED = 5;
The QUEUED 6;
Body SMS content
service_center SMS service center number number
The theme of the subject SMS
reply_path_present TP-Reply-Path
locked
*
*
* */
private static final String Address = "address";
    Cursor cur;
    public List<smsfetch> getAllsms(int requestfor,String PersonSMS){
//        myWritableDb=this.getReadableDatabase();
        List<smsfetch> allsms=new ArrayList<smsfetch>();
PrintMsg.setLogerror(context,"Step1");

        final String SMS_URI_ALL = "content://sms/";
        Uri uri = Uri.parse(SMS_URI_ALL);
        ContentResolver cr = context.getContentResolver();
        String[] projection = new String[] { "_id", "(CASE WHEN length(address)==13 THEN substr(address,4,12) WHEN length(address)==12 THEN substr(address,3,11) ELSE address END) as addrs", "person", "body", "date", "type" ,"protocol","read","status","subject"};

//        String[] projection = new String[] { "_id", " (CASE WHEN length(REPLACE(address,' ',''))==13 THEN substr(substr(REPLACE(address,' ',''),0,4)='+91',4,12)  WHEN length(REPLACE(address,' ',''))==12 THEN substr(substr(REPLACE(address,' ',''),0,3)='91',3,11)   ELSE REPLACE(address,' ','') END) as addrs", "person", "body", "date", "type" ,"protocol","read","status","subject"};

        PrintMsg.setLogerror(context,"Step2");




        if(requestfor==1) {

//            cr.query(uri, new String[]{"DISTINCT address"},"address IS NOT NULL) GROUP BY (address", null, null);
//            finalCC = Message_distiencodenct;

            //WILL GET ALL PRIVATE & SPAM ADDRESS LIST
            ArrayList<String> AddList=getPrivate_spam(0);

            String Allwhere=" address NOT IN  "+argsArrayToString(AddList)+" AND address IS NOT NULL) GROUP BY (addrs";
//            String Allwhere=" address NOT IN  "+argsArrayToString(AddList)+" AND address IS NOT NULL ) GROUP BY (address";
            PrintMsg.setLogerror(context,"------>"+Allwhere);
            cur = cr.query(uri, projection,Allwhere, null , "date asc");
        }


        if(requestfor==2) {

            //WILL GET ALL SPAM ADDRESS LIST

            ArrayList<String> AddList=getPrivate_spam(1);
            String Spamwhere=" address  IN  "+argsArrayToString(AddList)+" AND address IS NOT NULL ) GROUP BY (addrs";
            cur = cr.query(uri, projection,Spamwhere, null, "date asc");
        }


        if(requestfor==3) {

            //WILL GET ALL PRIVATE ADDRESS LIST
            ArrayList<String> AddList=getPrivate_spam(2);
            String Privatespam=" address  IN  "+argsArrayToString(AddList)+" AND address IS NOT NULL) GROUP BY (addrs";
            cur = cr.query(uri, projection,Privatespam, null, "date asc");
        }


//        getContactName("9550092677");

            PrintMsg.setLogerror(context, "Step4 " + cur.getCount());
            String Addres,SenderMessage,FinalMessage;
        String[] ProcessMessage;
            while (cur.moveToNext()) {
                int index_ID = cur.getColumnIndex("_id");
                int index_Address = cur.getColumnIndex("addrs");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");
                int index_protocol = cur.getColumnIndex("protocol");
                int index_read = cur.getColumnIndex("read");
                int index_status = cur.getColumnIndex("status");
                int index_subject = cur.getColumnIndex("subject");

                Addres = cur.getString(index_Address);

//                if (Addres.contains("WAYSMS")) {
//                    SenderMessage=cur.getString(index_Body);
//                    String[] Number = SenderMessage.split(":");
//                    if (Number[0] != null && Number[0].length() > 9) {
////                        if (Number[1].contains("Reply via WAY2SMS")) {
//                            ProcessMessage = Number[1].split("-");
//
//
//                            //ACTUAL MESSAGE HERE... AFTER SPLITTING
//                           FinalMessage = ProcessMessage[0];
//                            Log.e("Way2SMS sms splitted :","---"+FinalMessage+""+Number[0]);
//                            smsfetch fetch = new smsfetch(cur.getString(index_ID), Number[0], Number[0], FinalMessage, cur.getString(index_read), cur.getString(index_protocol), cur.getString(index_Date), cur.getString(index_Type), cur.getString(index_status), cur.getString(index_subject));
//                            allsms.add(fetch);
//
////                        }
//                    }
//                } else {
//                    Log.e("SMS  :","---"+Addres+"---"+cur.getString(index_read));
                    smsfetch fetch = new smsfetch(cur.getString(index_ID), Addres, Addres, cur.getString(index_Body), cur.getString(index_read), cur.getString(index_protocol), cur.getString(index_Date), cur.getString(index_Type), cur.getString(index_status), cur.getString(index_subject));
//            PrintMsg.setLogerror(context,cur.getString(index_ID)+"---"+Addres+"---"+getContactName(context,Addres)+"---"+cur.getString(index_Body)+"---"+cur.getString(index_read)+"---"+cur.getString(index_protocol)+"---"+cur.getString(index_Date)+"---"+cur.getString(index_Type)+"---"+cur.getString(index_status));
                    allsms.add(fetch);

//                }
            }

        PrintMsg.setLogerror(context,"Step5");
        cur.close();

        return allsms;
    }
    public int getCount(String Address) {
        Cursor c = null;
        try {
            myWritableDb = this.getReadableDatabase();
            String query = "select count(*) from "+PRIVATE_TABLE+" where p_mobileno = ?";
            c = myWritableDb.rawQuery(query, new String[] {Address});
            if (c.moveToFirst()) {
                return c.getInt(0);
            }
            return 0;
        }
        finally {
            if (c != null) {
                c.close();
            }
            if (myWritableDb != null) {
                myWritableDb.close();
            }
        }
    }

    String prevDate;
public  ArrayList<item> stickyheader(String PersonSMS){
    ArrayList<item> items = new ArrayList<item>();
    final String SMS_URI_ALL = "content://sms/";
    Uri uri = Uri.parse(SMS_URI_ALL);
    ContentResolver cr = context.getContentResolver();
    String[] projection = new String[] { "_id", Address, "person", "body", "date", "type" ,"protocol","read","status","subject"};

    cur = cr.query(uri, projection,Address+ " ='" +PersonSMS+ "' or "+Address+ " ='+91" +PersonSMS+ "' or "+Address+ " ='91" +PersonSMS+"'", null, "date asc");

String Addres;
    while (cur.moveToNext()){
    int index_ID = cur.getColumnIndex("_id");
    int index_Address = cur.getColumnIndex("address");
    int index_Person = cur.getColumnIndex("person");
    int index_Body = cur.getColumnIndex("body");
    int index_Date = cur.getColumnIndex("date");
    int index_Type = cur.getColumnIndex("type");
    int index_protocol = cur.getColumnIndex("protocol");
    int index_read = cur.getColumnIndex("read");
    int index_status = cur.getColumnIndex("status");
    int index_subject = cur.getColumnIndex("subject");
//            prevDate=getDateheader(Long.valueOf(model.getTime()));
        Addres = cur.getString(index_Address);
        String thisDate = getDateheader(Long.valueOf(cur.getString(index_Date)));
//        PrintMsg.setLogerror(context, "this is model11111111111 " + prevDate);
//        PrintMsg.setLogerror(context, "this is mode222222222222 " + thisDate);
        if (prevDate == null) {
            prevDate=thisDate;
            items.add(new SectionItem(thisDate));
            items.add(new smsfetch(cur.getString(index_ID), Addres, Addres, cur.getString(index_Body), cur.getString(index_read), cur.getString(index_protocol), cur.getString(index_Date), cur.getString(index_Type), cur.getString(index_status), cur.getString(index_subject)));

        }
        else  if (!prevDate.equals(thisDate)) {

            items.add(new SectionItem(thisDate));
            items.add(new smsfetch(cur.getString(index_ID), Addres, Addres, cur.getString(index_Body), cur.getString(index_read), cur.getString(index_protocol), cur.getString(index_Date), cur.getString(index_Type), cur.getString(index_status), cur.getString(index_subject)));


        } else {

            items.add(new smsfetch(cur.getString(index_ID), Addres, Addres, cur.getString(index_Body), cur.getString(index_read), cur.getString(index_protocol), cur.getString(index_Date), cur.getString(index_Type), cur.getString(index_status), cur.getString(index_subject)));

        }
        prevDate = thisDate;
//        PrintMsg.setLogerror(context, "this is model" + prevDate);

}
    cur.close();
    return items;
}

    String res;
    private String getDateheader(Long dbtime){
        DateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
        //Converting milliseconds to Date using Calendar
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dbtime);
        res=df.format(cal.getTime());
        return res;
    }

    String argsArrayToString(List<String> args) {
        StringBuilder argsBuilder = new StringBuilder();
        argsBuilder.append("(");
        final int argsCount = args.size();
        for (int i=0; i<argsCount;i++) {
            argsBuilder.append("'"+args.get(i)+"'");
            if (i < argsCount - 1) {
                argsBuilder.append(",");
            }
        }
        argsBuilder.append(")");
        return argsBuilder.toString();
    }


    public int getTypeCount(String Address,String type) {
        Cursor c = null;
        try {
            myWritableDb = this.getReadableDatabase();
            String query = "select count(*) from "+PRIVATE_TABLE+" where p_mobileno = ? and P_Type = ?";
            c = myWritableDb.rawQuery(query, new String[] {Address,type});
            if (c.moveToFirst()) {
                return c.getInt(0);
            }
            return 0;
        }
        finally {
            if (c != null) {
                c.close();
            }
            if (myWritableDb != null) {
                myWritableDb.close();
            }
        }
    }

    public void insertPrivate_Spam(String address, int type) {

        if(getCount(address)==0){
            myWritableDb = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(P_ADDRESS, address);
            values.put(P_TYPE, type);
            myWritableDb.insert(PRIVATE_TABLE, null, values);
        }else{
            myWritableDb = this.getWritableDatabase();
            myWritableDb.delete(PRIVATE_TABLE,P_ADDRESS+" =?",new String[]{address});
        }

    }

    public ArrayList<String> getPrivate_spam(int i) {
        myWritableDb=this.getReadableDatabase();
        ArrayList<String> ps_list=new ArrayList<>();
        Cursor cur;


        if(i==0)
            cur=myWritableDb.query(PRIVATE_TABLE, null, null, null, null, null, null);
        else
            cur=myWritableDb.query(PRIVATE_TABLE, null, P_TYPE+" =?", new String[]{String.valueOf(i)}, null, null, null);



        while (cur.moveToNext()) {
            ps_list.add(cur.getString(cur.getColumnIndex(P_ADDRESS)));
        }
        return ps_list;
    }


//    String contactId = "";
//    String contactName = "";
//
//    private String getContactName(String phoneNo) {
//        try{
//            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
//            String[] projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };
//            String selection = null;
//            String[] selectionArgs = null;
//            String sortOrder = ContactsContract.PhoneLookup.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
//            ContentResolver cr = context.getContentResolver();
//            if(cr != null){
//                Cursor resultCur = cr.query(uri, projection, selection, selectionArgs, sortOrder);
//                if(resultCur != null){
//                    while (resultCur.moveToNext()) {
////                        contactId = resultCur.getString(resultCur.getColumnIndex(ContactsContract.PhoneLookup._ID));
//                        contactName = resultCur.getString(resultCur.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
//
//                    }
//                    resultCur.close();
//                }else{
//                    contactName=phoneNo;
//                }
//            }
//        }
//        catch(Exception sfg){
//            Log.e("Error", "Error in loadContactRecord : "+sfg.toString());
//        }
//
//        return contactName;
//    }//fn retrieveContactRecord

    String contactName = null;

    private static final String[] PROJECTION = new String[] {
            ContactsContract.Data.DISPLAY_NAME,

    };
    Cursor cursor =null;

    long contactId;
    String displayName, address;
//    Uri   puri = Uri.parse("content://com.android.contacts/phone_lookup");
    Uri puri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI,null
    );

    public String getContactName(String phoneNumber,ContentResolver cr) {

        cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, ContactsContract.PhoneLookup.NUMBER+" = '"+phoneNumber+"'", null, null);
        final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        if (cursor != null) {
            try {

                while (cursor.moveToNext()) {
                    contactName = cursor.getString(displayNameIndex);
                }
            } finally {
                cursor.close();
            }
        }

        return contactName;
    }

//    String contactName = "";
//    public String getContactName(final String phoneNumber) {
//        if (phoneNumber != null){
//            Uri uri;
//        String[] projection;
//
//        if (Build.VERSION.SDK_INT >= 5) {
//            uri = Uri.parse("content://com.android.contacts/phone_lookup");
//            projection = new String[]{"display_name"};
//        } else {
//            uri = Uri.parse("content://contacts/phones/filter");
//            projection = new String[]{"name"};
//        }
//
//        uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber));
//        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
//
//
//
//        if (cursor.moveToFirst()) {
//            contactName = cursor.getString(0);
//        }
//
//        cursor.close();
//        cursor = null;
//    }else{
//            contactName=phoneNumber;
//        }
//        return contactName;
//    }
}
